package com.learn.base.aspect;

import cn.hutool.core.util.StrUtil;
import com.learn.base.annotation.RedisLock;
import com.learn.base.utils.SpelUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author : Yu.Tan
 * @date : 2023/1/17 10:54
 * @desc : **
 */
@Component
@Aspect
@Slf4j
public class RedisLockAspect {
    @Autowired
    private RedissonClient redissonClient;

    private static final String REDISSON_LOCK_PREFIX="redisson_lock:";

    @Around("@annotation(redisLock)")
    public Object around(ProceedingJoinPoint joinPoint, RedisLock redisLock) throws Throwable {

        String spel = redisLock.key();
        String lockName = redisLock.lockName();

        String redisKey = getRedisKey(joinPoint, lockName, spel);
        log.info(redisKey);
        RLock lock = redissonClient.getLock(redisKey);
        lock.lock(redisLock.expire(),redisLock.timeUnit());
        Object result = null;
        try {
            //执行方法
            result = joinPoint.proceed();

        } finally {
            lock.unlock();
        }
        return result;
    }

    public String getRedisKey(ProceedingJoinPoint joinPoint,String lockName,String spel){
        //获取封装了部署信息的对象，在该对象中可以获取到目标方法名，所属类的Class等信息
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature=(MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        //获取被代理的对象
        Object target = joinPoint.getTarget();
        //获取传入目标方法的参数对象
        Object[] args = joinPoint.getArgs();
        return REDISSON_LOCK_PREFIX + lockName + StrUtil.COLON + SpelUtil.parse(target,spel, targetMethod, args);
    }



}
